package top.wangjingxin.service;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.wangjingxin.base.Result;
import top.wangjingxin.dao.DownloadDao;
import top.wangjingxin.model.annex.AnnexDTO;
import top.wangjingxin.util.DeleteUtil;
import top.wangjingxin.util.UuidUtil;

import java.io.File;
import java.io.IOException;

import static top.wangjingxin.cache.ResultCache.FAILURE;
import static top.wangjingxin.cache.ResultCache.OK;
import static top.wangjingxin.cache.ResultCache.getDataOk;
import static top.wangjingxin.config.AppConfig.ROOT;
import static top.wangjingxin.util.SessionUtil.response;

@Service
public class DownloadService {
    @Autowired
    DownloadDao downloadDao;

    public Result show(String id) {
        return getDataOk(downloadDao.show(id));
    }

    @Transactional
    public Result upload(MultipartFile file) {
        AnnexDTO dto = new AnnexDTO();
        dto.setId(UuidUtil.Uuid());
        dto.setName(file.getOriginalFilename());
        try {
            File f = new File(ROOT + File.separator + "resource" + File.separator + dto.getId() + File.separator + dto.getName());
            f.getParentFile().mkdirs();
            file.transferTo(f);
            downloadDao.insert(dto);
        } catch (IOException e) {
            e.printStackTrace();
            return FAILURE;
        }
        return getDataOk(dto.getId());
    }

    public Result delete(String id) {
        if (downloadDao.delete(id) == 1) {
            DeleteUtil.delete(id);
            return OK;
        }
        return FAILURE;
    }

    public ResponseEntity<byte[]> get(String id) {
        downloadDao.update(id);
        File[] files = new File(ROOT + File.separator + "resource" + File.separator + id).listFiles();
        if (files.length == 0) {
            return null;
        }
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", new String(files[0].getName().getBytes("utf-8"),"ISO8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(FileUtils.readFileToByteArray(files[0]), headers, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
